export interface IDot {
    x:number
    y:number
    context:CanvasRenderingContext2D
    size:number
}

export default class Dot{

    private readonly _context:CanvasRenderingContext2D;
    private _x:number;
    private _y:number;
    private _radian:number;
    private readonly _size:number;
    private readonly _color:string;
    private _speed:number;
    constructor(props:IDot){
        const {x, y, context, size} = props;
        this._x = x;
        this._y = y;
        this._context = context;
        this._size = size;
        this._speed = Math.round(Math.random() * 8) + 3;
        this.draw();
        this. _color = `rgb(
            ${Math.floor(Math.random()*255)},
            ${Math.floor(Math.random()*255)},
            ${Math.floor(Math.random()*255)})`;
    }

    /**
     * 绘制dot
     */
    draw():number{
        const context = this._context;
        context.fillStyle = this._color;
        context.fillRect(this._x, this._y, this._size, this._size);
        return 1;
    }


    /**
     * 用于移动dot
     * @param target_x
     * @param target_y
     */
    move(target_x: number, target_y: number){
        const distance_y = target_y - this._y;
        const distance_x = target_x - this._x;
        const offset = 10;
        this._radian = Math.atan2(distance_y,distance_x);
        if(Math.abs(this._x-target_x)<offset){
            this._x = target_x;
        }else{
            this._x += this._speed * Math.cos(this._radian);
        }
        if(Math.abs(this._y-target_y) <offset){
            this._y = target_y;
        }else{
            this._y += this._speed * Math.sin(this._radian);
        }
        this.draw();
    }
}